//
//  EpointContactsListViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 13-12-17.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "EpointContactsListViewController.h"
#import "EpointContactsDetailViewController.h"
#import "UIImage+Tint.h"
#import "EpointPersonChooseListCell.h"
#import "EpointContactsDetailsViewController.h"


#import "FPPopoverController.h"
#import "PGTitleView.h"
#import "PopElementView.h"
#import "EpointScrollTap.h"
#import "ContactModel.h"
#import "ContactUserCell.h"

#define QueryTaskID 1
#define getAllUserTaskId 2

@interface EpointContactsListViewController ()<UITableViewDataSource,UITableViewDelegate, FPPopoverControllerDelegate, PGTitleViewDelegate, PopElementViewDelegate,EpointScrollTapDelegate>
{
    
    NSMutableArray *dataArray,*flagArr;
    NSMutableArray *alluserArray;
    UITableView *tv;
    
    
    
    UISearchBar *sb;
    UISearchDisplayController *searchController;
    
    NSArray *titles;
    
    UITableView *userTableView;//用户列表
}

@property(nonatomic,retain)NSMutableArray *indexArray;
//设置每个section下的cell内容
@property(nonatomic,retain)NSMutableArray *LetterResultArr;

@property (nonatomic, strong) FPPopoverController *popoverCtrl;
@property (nonatomic, strong) PGTitleView *titleView;
@property (nonatomic, strong) PopElementView *elementView;

@end

@implementation EpointContactsListViewController
@synthesize indexArray;
@synthesize LetterResultArr;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dataArray = [[NSMutableArray alloc]init];
        flagArr = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    [self setTitleView];//设置对话框列表标题
    
    sb = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, AppWidth, 44)];
    sb.placeholder = @"搜索";
    [self.view addSubview:sb];
    
    tv = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, AppWidth, UIViewRemain-44)];
    tv.tag = 1;
    tv.dataSource = self;
    tv.delegate = self;
    tv.hidden = NO;
    [self.view addSubview:tv];
    
    
    //添加用户列表TableView
    userTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, AppWidth, UIViewRemain-44)];
    userTableView.tag = 2;
    userTableView.dataSource = self;
    userTableView.delegate = self;
    userTableView.hidden = YES;
    [self.view addSubview:userTableView];
    
    
    
    sb.delegate = self;
    searchController = [[UISearchDisplayController alloc]initWithSearchBar:sb contentsController:self];
    searchController.searchResultsTableView.hidden = YES;
    searchController.searchResultsTableView.backgroundColor = [UIColor clearColor];
    searchController.searchResultsTableView.separatorColor = [UIColor clearColor];
    searchController.delegate = self;
    searchController.searchResultsDataSource = self;
    searchController.searchResultsDelegate = self;
    searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLineEtched;
    searchController.searchResultsTableView.bounces = NO;
    searchController.searchResultsTableView.tag = 3;
    [self getData:@""];
    
    
    
}

- (void)setTitleView {
    self.titleView = [[PGTitleView alloc] initWithFrame:CGRectZero];
    _titleView.text = @"群组";
    _titleView.delegate = self;
    NSArray* titleTaps = @[@"群组",@"人员"];
    
    EpointScrollTap * scrollTap = [[EpointScrollTap alloc] initWithFrame:CGRectZero:titleTaps];
    scrollTap.delegate = self;
    if (CurrentDeviceISiPad) {
        [self.navigationItem setTitleView:scrollTap];
    }else{
        [self.navigationItem setTitleView:self.titleView];
    }
    
}
//pad title选择 索引回调
-(void)selectIndexTitle_Pad:(int)index{
    [self popElementViewDidSelectedAtIndex:index];
}

- (FPPopoverController *)popoverCtrl {
    if (_popoverCtrl == nil) {
        titles = @[@"群组", @"人员"];
        _elementView = [[PopElementView alloc] initWithFrame:CGRectMake(0, 0, 160, PopElementItemHeight*2)];
        _elementView.delegate = self;
        _elementView.titles = titles;
        [_elementView selectItemAtIndex:0];
        
        _popoverCtrl = [[FPPopoverController alloc] initWithView:_elementView];
        _popoverCtrl.arrowDirection = FPPopoverArrowDirectionUp;
        _popoverCtrl.contentSize = CGSizeMake(170, PopElementItemHeight*2+10+FP_POPOVER_ARROW_HEIGHT);
        _popoverCtrl.delegate = self;
    }
    return _popoverCtrl;
}

#pragma mark - FPPopoverControllerDelegate

-(void)popoverControllerDidDismissPopover:(FPPopoverController *)popoverController{
    _titleView.isSelected = NO;
}

-(void)presentedNewPopoverController:(FPPopoverController *)newPopoverController shouldDismissVisiblePopover:(FPPopoverController *)visiblePopoverController{
}

- (void)titleViewDidSelected:(PGTitleView *)titleView {
    if (!self.popoverCtrl.showed) {
        [_popoverCtrl presentPopoverFromView:_titleView];
    }
}


#pragma mark 列表对话框点击事件
- (void)popElementViewDidSelectedAtIndex:(int)index {
    NSLog(@"index:%d", index);
    //    [self switchWithIndex:index];
    _titleView.text = [titles objectAtIndex:index];
    [_popoverCtrl dismissPopoverAnimated:YES];
    if(index==0){
        tv.hidden = NO;
        userTableView.hidden = YES;
    }else{
        tv.hidden = YES;
        userTableView.hidden = NO;

        #pragma mark -初始化用户列表
        if(alluserArray==nil || !alluserArray.count>0){
            [self getAllUser];
         }
       
    }
}

-(void)getAllUser{
    [self showMBPHUD];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [self startTask:@"Task_GetAllUser" withParams:params withTaskId:getAllUserTaskId];

}


-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:NO];
    [userTableView setHidden:YES];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView
{
    [tv setHidden:YES];
    [userTableView setHidden:YES];
}

//-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
//{
//    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
//    [params setObject:searchText forKey:@"keyword"];
//    [self startTask:@"EpointQueryContactsTask" withParams:params withTaskId:QueryTaskID];
//}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"searchBarSearchButtonClicked");
    [searchBar resignFirstResponder];
    [self doSearch:searchBar];
    
    [searchController setActive:NO animated:YES];
}

- (void)doSearch:(UISearchBar *)searchBar{
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:searchBar.text forKey:@"keyword"];
    [self startTask:@"EpointQueryContactsTask" withParams:params withTaskId:QueryTaskID];
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    sb.showsCancelButton = NO;
}

-(void)upLevel
{
    if (flagArr.count==0) {
        
    }
    else if(flagArr.count==1)
    {
        [self getData:@""];
    }
    else
    {
        [self getData:[flagArr objectAtIndex:flagArr.count - 2]];
    }
    
    if (flagArr.count>0) {
        [flagArr removeObjectAtIndex:flagArr.count-1];
        if (flagArr.count==0) {
            self.navigationItem.rightBarButtonItem = nil;
        }
    }
}

-(void)getData:(NSString *)_parentguid
{
    dataArray = [DBFrameService getContactsListByParentGuid:_parentguid];
    [searchController.searchResultsTableView reloadData];
    [tv reloadData];
}

-(void)getAllUserData
{
    alluserArray = [DBFrameService getAllUser];
}



-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag==1 || tableView.tag==3){
        static NSString *identifier = @"EpointPersonChooseListCell";
        EpointPersonChooseListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell==nil) {
            NSString *nibName = @"EpointPersonChooseListCell";
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:nibName owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        
        cell.backgroundColor = [UIColor clearColor];
        
        NSMutableDictionary *m = [dataArray objectAtIndex:indexPath.row];
        NSString *type = [m objectForKey:@"type"];
        cell.lbTitle.text = [m objectForKey:@"name"];
        [cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
        cell.lbTitle.textColor = COLOR(90, 68, 103);
        if ([type isEqualToString:@"user"]) {
            [cell.ivHead setImage:[UIImage imageNamed:@"img_personchoose_user"]];
            NSString *ouname = [m objectForKey:@"ouname"];
            NSString *title = [m objectForKey:@"title"];
            NSString *mobile = [m objectForKey:@"mobile"];
            if(mobile==nil || [mobile isEqual:@""]){
                cell.lbTitle.text = [m objectForKey:@"name"];
            }else{
                cell.lbTitle.text =[NSString stringWithFormat:@"%@:%@",[m objectForKey:@"name"],mobile];
            }
            
            if(title==nil || [title isEqual:@""]){
                cell.lbDetail.text = ouname;
            }else{
                cell.lbDetail.text = [NSString stringWithFormat:@"%@:%@",ouname,title];
            }
            
            cell.lbDetail.hidden = NO;
            cell.ivCheck.hidden = YES;
        }
        else
        {
            [cell.ivHead setImage:[UIImage imageNamed:@"img_personchoose_ou"]];
            cell.textLabel.textColor = [UIColor blackColor];
            cell.detailTextLabel.text = @"";
            cell.ivCheck.hidden = YES;
            cell.lbTitle.center = CGPointMake(165,47/2);
            cell.lbDetail.hidden = YES;
        }
        
        return cell;
    }else if(tableView.tag==2){
        static NSString *CellIdentifier = @"ContactUserCellID";
        ContactUserCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell==nil) {
            NSString *nibName = @"ContactUserCell";
            NSArray *nib = [[NSBundle mainBundle]loadNibNamed:nibName owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
//        NSArray *textArray =[[[self.LetterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row] componentsSeparatedByString:@";"];
//        if (textArray.count<3) {
//            NSLog(@"textArray.count<3");
//        }else{
//            cell.nameLabel.text = [textArray objectAtIndex:0];
//            cell.phoneLabel.text = [textArray objectAtIndex:2];
//        }
        
        return cell;
    }
    return nil;
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag==1 || tableView.tag==3){
        return 47;
    }else{
        return 51;
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag==1 || tableView.tag==3) {
        return dataArray.count;
    }else{
//        return [[self.LetterResultArr objectAtIndex:section] count];
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(tableView.tag==1){
        NSMutableDictionary *m = [dataArray objectAtIndex:indexPath.row];
        NSString *guid = [m objectForKey:@"guid"];
        NSString *type = [m objectForKey:@"type"];
        if ([type isEqualToString:@"ou"])
        {
            [self getData:guid];
            [flagArr addObject:guid];
            [self setRightBarButtonItemWithTitle:@"上级" action:@selector(upLevel)];
        }
        else if([type isEqualToString:@"user"])
        {
            NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
            [params setObject:[m objectForKey:@"name"] forKey:@"title"];
            [params setObject:[m objectForKey:@"guid"] forKey:@"userguid"];
            EpointContactsDetailsViewController *dv = [[EpointContactsDetailsViewController alloc]initWithParams:params];
            [self.navigationController pushViewController:dv animated:YES];
        }
    }else{
//        NSArray *temp =[[[self.LetterResultArr objectAtIndex:indexPath.section]objectAtIndex:indexPath.row] componentsSeparatedByString:@";"];
//        NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
//        int index =[[temp objectAtIndex:1]intValue];
//        ContactModel *m = [alluserArray objectAtIndex:index];
//        [params setObject:m.displayname forKey:@"title"];
//        [params setObject:m.userguid forKey:@"userguid"];
//        EpointContactsDetailsViewController *dv = [[EpointContactsDetailsViewController alloc]init];
//        dv.passParam = params;
//        [self.navigationController pushViewController:dv animated:YES];
    }
    
}

#pragma mark -刷新
-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    [self hideMBPHUD];
    if(taskId==QueryTaskID){
        dataArray = (NSMutableArray *)obj;
        [tv reloadData];
        [searchController.searchResultsTableView reloadData];
    }else if(taskId == getAllUserTaskId){
        alluserArray =  (NSMutableArray *)obj;;
        NSLog(@"%i",alluserArray.count);
        
        NSString *usertemp = nil;
        for (int i=0; i<alluserArray.count; i++) {
            ContactModel *m = [alluserArray objectAtIndex:i];
            usertemp =[NSString stringWithFormat:@"%@<>%@;%i;%@",usertemp,m.displayname,i,m.mobile];
        }
        NSArray *stringsToSort = [usertemp componentsSeparatedByString:@"<>"];
        self.indexArray = [ChineseString IndexArray:stringsToSort];
        self.LetterResultArr = [ChineseString LetterSortArray:stringsToSort];
        [userTableView reloadData];
    }
    
}

#pragma mark -Section的Header的值
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (tableView.tag==2) {
        NSString *key = [indexArray objectAtIndex:section];
        return key;
    }else{
        return nil;
    }
}
#pragma mark - 自定义Section header view
//-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
//    if(tableView.tag==2){
//        UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 320, 20)];
//        lab.backgroundColor = [UIColor lightGrayColor];
//        lab.text =[NSString stringWithFormat:@"   %@",[indexArray objectAtIndex:section]];
//        lab.textColor = [UIColor whiteColor];
//        return lab;
//    }else{
//        return nil;
//    }
//    
//}
#pragma mark -设置右方表格的索引数组
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView.tag==2) {
        return indexArray;
    }else{
        return nil;
    }
    
}
#pragma mark -设置分区个数
//- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
//{
//    if (tableView.tag==2) {
////        NSLog(@"title===%@",title);
//    NSLog(@"index=%i",index);
//        return index;
//    }else{
//        return 1;
//    }
//}

#pragma mark -允许数据源告知必须加载到Table View中的表的Section数。
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView.tag==2) {
        NSLog(@"numberOfSectionsInTableView=%i",indexArray.count);
        return [indexArray count];
    }else{
        return 1;
    }
}



@end
